<?php
/**
 * 发送短信验证码
 * Created by PhpStorm.
 * User: admin
 * Date: 2017/5/9
 * Time: 22:49
 */

namespace App\Utils;

use Illuminate\Support\Facades\Log;

class Sms
{

    const APP_KEY = '3e28829503e3e1397554577b349d8562';//您申请的APPKEY
    const REG_LOGIN_TPL_ID = 217208;//您申请的短信模板ID，根据实际情况修改
    const SEND_URL = 'http://v.juhe.cn/sms/send';//请求地址


    public function sendSms($tel, $code, $tplId = self::REG_LOGIN_TPL_ID)
    {
        $smsConf = array(
            'key' => self::APP_KEY,
            'mobile' => $tel, //接受短信的用户手机号码
            'tpl_id' => $tplId,
            'tpl_value' => urlencode('#code#=' . $code)
        );
        $content = $this->juheCurl($smsConf, 0); //请求发送短信
        if ($content) {
            $result = json_decode($content, true);
            $error_code = $result['error_code'];
            if ($error_code == 0) {
                return true;
            } else {
                //状态非0，说明失败
                $error = $result['reason'];
                Log::error('短信发送失败:', [$tel, $error]);
                return false;
            }
        } else {
            Log::error('短信发送失败:', [$tel, '请求发送短信失败']);
            return false;
        }
    }
    /**
     * 请求接口返回内容
     * @param  string $url [请求的URL地址]
     * @param  array $params [请求的参数]
     * @param  int $ipost [是否采用POST形式]
     * @return  string
     */
    private function juheCurl($params = null, $ispost = 0)
    {
        $url = self::SEND_URL;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22');
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        if ($ispost) {
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
            curl_setopt($ch, CURLOPT_URL, $url);
        } else {
            if ($params) {
                $str = '';
                foreach ($params as $key => $value)
                {
                    $str .= $key.'='.$value.'&';
                }
                curl_setopt($ch, CURLOPT_URL, $url . '?' . $str);
            } else {
                curl_setopt($ch, CURLOPT_URL, $url);
            }
        }
        $response = curl_exec($ch);
        curl_close($ch);
        return $response;
    }
}
